import { getUserInfoAPI } from "@/apis/user"
import { getToken as _getToken, setToken as _setToken, removeToken } from "@/utils"
import { createSlice } from "@reduxjs/toolkit"
const tokenStore = createSlice(
    {
        name: "tokenStore",
        initialState: {
            token: _getToken() || "",
            userInfo: {},
        },
        reducers: {
            setToken(state, action) {
                state.token = action.payload
                //持久化存储
                _setToken(action.payload)
            },
            setUserInfo(state, action) {
                state.userInfo = action.payload
            },
            clearUser(state) {
                state.token = ""
                state.userInfo = {}
                removeToken()
            }
        }
    }
)

//编写异步action去后端获取userInfo
const getUserInfo = () => {
    return (dispatch) => {
        //获取userinfo
        getUserInfoAPI().then(
            res => {
                //存储store
                dispatch(setUserInfo(res.data.data))

            }
        )


    }
}
//解构actioncreater
const { setToken, setUserInfo, clearUser } = tokenStore.actions
//解构出reducer
const tokenReducer = tokenStore.reducer
//按需导出actioncreater
export { clearUser, getUserInfo, setToken, setUserInfo }
//默认导出reducer
export default tokenReducer